package com.m1905hd.user.web.controller

import com.m1905hd.common.global.JSONCode
import com.m1905hd.common.util.JSONUtil
import com.m1905hd.user.entity.Resource
import com.m1905hd.user.service.ResourceService
import com.m1905hd.user.web.PKUtil
import org.apache.shiro.authz.annotation.RequiresPermissions
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.util.StringUtils
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod

/**
 *
 * @author weiwei.huang
 * @email ihuangweiwei@163.com
 * @date 15/3/30
 */
@Controller
@RequestMapping("resource")
class ResourceController {


    @Autowired
    ResourceService resourceService

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @RequiresPermissions("resource:view")
    def showList(Model model) {
        List<Resource> resourceList = this.resourceService.findAll()
        model.addAttribute("data", JSONUtil.beanToJson(PKUtil.buildTree(resourceList)))
        return "resource/list"
    }


    @RequestMapping(value = "edit.json")
    @RequiresPermissions("resource:edit")
    def edit(Resource resource) {
        resource.parentIds = "0"
        if (resource.parentId != 0) {
            Resource parentResource = this.resourceService.find(resource.parentId)
            if (!parentResource.parentIds.equals("0") && !StringUtils.isEmpty(parentResource.parentIds)) {
                resource.parentIds = parentResource.parentIds + "," + parentResource.id
            } else {
                resource.parentIds = parentResource.id
            }
        }
        resource.id == 0 ? this.resourceService.create(resource) : this.resourceService.update(resource)
        [code: JSONCode.SUCCESS.code]
    }


    @RequestMapping("delete/{id}")
    @RequiresPermissions("resource:edit")
    def delete(@PathVariable("id") int id) {
        Resource resource = this.resourceService.findByParentId(id)
        if (resource == null) {
            this.resourceService.delete(id)
            return [code: JSONCode.SUCCESS.code]
        }
        return [code: JSONCode.ERROR.code, msg: "请先删除子节点"]
    }

}
